﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Linq;
using VerificationCode.Model;
using WenZhi = VerificationCode.Dal.WenZhi;

namespace VerificationCode
{
    public class Code
    {
        private readonly WenZhi _wenZhiDal = new WenZhi();
        public Model.Code GetCode()
        {
          
            var wenzlist = _wenZhiDal.GetCodeText();  //获取验证码
            var listAnsuwr = new List<Answer>();//实例化备选答案对象
            var answerCode = string.Empty;//答案
            var result = new Model.Code
            {
                Id = Guid.NewGuid().ToString()
            };
            //根据验证码获取备选答案并把添加到答案添加到备选答案集合
            foreach (var item in wenzlist)
            {
                answerCode += item.ID + ",";
                result.AnswerValue += item.Text;
                var answerList = _wenZhiDal.GetAnswer(item.BuShouCode, item.ID);
                listAnsuwr.Add(new Answer { Id = item.ID.ToString(), Img = GetImage(item.Text) });
                listAnsuwr.AddRange(answerList.Select(answer => new Answer { Id = answer.ID.ToString(), Img = GetImage(answer.Text) }));
            }
            //如果答案个数不够就再去取几个
            if (listAnsuwr.Count < 9)
            {
                var ran = new Random();
                var randKey = ran.Next(0, 4);
                var item = wenzlist[randKey];
                var answerList = _wenZhiDal.GetAnswer(item.BuShouCode, item.ID, 9 - listAnsuwr.Count);
                listAnsuwr.AddRange(answerList.Select(answer => new Answer { Id = answer.ID.ToString(), Img = GetImage(answer.Text) }));
            }
            result.CodeImg = GetImage(result.AnswerValue);
            result.AnswerValue = answerCode.TrimEnd(',');
            result.Answer = RandomSortList(listAnsuwr);//打乱正确答案与形近字的顺序
            return result;
        }


        /// <summary>
        /// 随机排列集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="listT"></param>
        /// <returns></returns>
        private static List<T> RandomSortList<T>(IEnumerable<T> listT)
        {
            var random = new Random();
            var newList = new List<T>();
            foreach (var item in listT)
            {
                newList.Insert(random.Next(newList.Count + 1), item);
            }
            return newList;
        }

        private static string GetImage(string text)
        {
            Image image;
            switch (text.Length)
            {
                case 1:
                    image = new Bitmap(50, 40);
                    break;
                case 4:
                    image = new Bitmap(120, 40);
                    break;
                default:
                    image = new Bitmap(50, 40);
                    break;
            }
            Brush brushText = new SolidBrush(Color.FromArgb(255, 0, 0, 0));
            var graphics = Graphics.FromImage(image);
            graphics.SmoothingMode = SmoothingMode.AntiAlias;
            graphics.Clear(Color.White);
            var font = new Font(new FontFamily("华文彩云"), 20, FontStyle.Regular);
            //var font = new Font(new FontFamily("方正舒体"), 20);
            if (text.Length > 1)
            {
                graphics.DrawLine(new Pen(brushText, new Random().Next(1, 3)), new Point(new Random().Next(0, 10), new Random().Next(10, 40)), new Point(new Random().Next(100, 120), new Random().Next(10, 30)));
                graphics.DrawLine(new Pen(brushText, new Random().Next(1, 3)), new Point(new Random().Next(20, 50), new Random().Next(0, 10)), new Point(new Random().Next(100, 120), new Random().Next(30, 40)));
                graphics.DrawString(text, font, brushText, 0, 10);

            }
            else
            {
                Point middle = new Point(25, 20);
                graphics.TranslateTransform(middle.X, middle.Y);
                graphics.RotateTransform(new Random().Next(0, 360));
                var format = new StringFormat(StringFormatFlags.NoClip)
                {
                    Alignment = StringAlignment.Center,
                    LineAlignment = StringAlignment.Center
                };
                graphics.DrawString(text, font, brushText, 0, 0, format);

            }
            brushText.Dispose();
            graphics.Dispose();
            return ImageToBase64(image);
        }

        /// <summary>
        /// 图片转换成BASE64
        /// </summary>
        /// <param name="img"></param>
        /// <returns></returns>
        public static string ImageToBase64(Image img)
        {
            try
            {
                var ms = new MemoryStream();
                img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                var arr = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(arr, 0, (int)ms.Length);
                ms.Close();
                return Convert.ToBase64String(arr);
            }
            catch (Exception)
            {
                return "";
            }
        }

        /// <summary>
        /// base64 转换成图片
        /// </summary>
        /// <param name="base64"></param>
        /// <returns></returns>
        public static Image Base64ToImage(string base64)
        {
            try
            {
                var b = Convert.FromBase64String(base64);
                var ms = new MemoryStream(b);
                var bitmap = new Bitmap(ms);
                return bitmap;

            }
            catch (Exception)
            {
                return null;
            }
        }
    }
}
